package com.strongbj.iot.devices.hr.request.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.hr.message.HRMessageFactory;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.request.entity.BuzzerEntity;
import com.strongbj.iot.devices.hr.response.handle.HRResponseHandleContext;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelMatcher;

/**
 * 蜂鸣器命令的处理
 * 
 * @author yuzhantao
 *
 */
public class BuzzerHandle implements IMessageHandle<MQMessageOfHR, Object> {
	private static Logger logger = LogManager.getLogger(BuzzerHandle.class.getName());
	private final static String ACTION_CODE = "collect021";
	private HRMessageFactory hrFactory = new HRMessageFactory();

	@Override
	public boolean isHandle(MQMessageOfHR t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfHR t) {
		logger.info("HR 收到MQ发来的控制门禁报警信息 json={}", JSON.toJSONString(t));
		BuzzerEntity buzzer = ((JSONObject) t.getAwsPostdata()).toJavaObject(BuzzerEntity.class);
		// 预留关闭报警功能用
		if (!buzzer.isAlarm())
			return null;

		// 发送数据到门禁
		byte[] datas = this.messageDataToBytes(buzzer);
		ByteBuf bs = Unpooled.copiedBuffer(datas);
		HRResponseHandleContext.channels.writeAndFlush(bs, new MyChannelMatchers(buzzer.getDevIp()));
		logger.info("HR 发送门禁报警控制命令成功 message={}", ByteUtil.byteArrToHexString(datas));
		buzzer = null;
		return null;
	}

	private byte[] messageDataToBytes(BuzzerEntity buzzer) {
		// 计算重复次数（假定响1秒，停1秒）
		long repetitions = buzzer.getAlarmTime() / 10;
		byte[] datas = new byte[] { 10, 10, 0 };
		// 设置重复次数，如果重复次数超过255，就按255次执行
		datas[2] = (byte) Math.min((int) repetitions, 255);
		// 获取二进制的消息
		return hrFactory.createHRMessage((byte) 0x0F, (byte) 0x0, (byte) 0x0, datas);
	}

	class MyChannelMatchers implements ChannelMatcher {
		private String currentIP;

		public MyChannelMatchers(String ip) {
			this.currentIP = ip;
		}

		@Override
		public boolean matches(Channel channel) {
			InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
			if (insocket.getAddress().getHostAddress().equals(this.currentIP)) {
				return true;
			} else {
				return false;
			}
		}
	}
}
